﻿using _20_identity框架_01.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace _20_identity框架_01.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DemoController : ControllerBase
    {
        private readonly UserManager<MyUser> userManager;
        private readonly RoleManager<MyRoles> roleManager;
        private readonly IWebHostEnvironment webHostEnvironment;

        public  DemoController(UserManager<MyUser> userManager, RoleManager<MyRoles> roleManager, IWebHostEnvironment webHostEnvironment)
        {
            this.userManager = userManager;
            this.roleManager = roleManager;
            this.webHostEnvironment = webHostEnvironment;
        }
        [HttpPost]
        public async Task<ActionResult<string>> AddRoles()
        {
            if (await roleManager.RoleExistsAsync("admin") == false)
            {
                MyRoles role = new MyRoles
                {
                    Name = "admin"
                };
               var result=  await roleManager.CreateAsync(role);
                if (result.Succeeded == false)
                {
                    return BadRequest("创建校色失败");
                }
            }
            MyUser user1 = await userManager.FindByNameAsync("yzk");
            if (user1 == null)
            {
                user1 = new MyUser {
                    UserName = "yzk"
                };
                var result1=await userManager.CreateAsync(user1, "123456");
                if (!result1.Succeeded)
                {
                    return BadRequest("创建用户失败");
                }
            }
            if (!await userManager.IsInRoleAsync(user1, "admin"))
            {
                var result2= await userManager.AddToRoleAsync(user1, "admin");
                if (!result2.Succeeded) return BadRequest("用户，角色关联表创建失败");
            }
            return Ok("创建成功");
        }

        [HttpPost]
        public async Task<ActionResult> CheckPwd(CheckPwdRequest req)
        {
            string userName = req.UserName;
            string pwd = req.passWord;

            var user=await userManager.FindByNameAsync(userName); //判断用户是否存在
            if (user == null)
            {
                if (webHostEnvironment.IsDevelopment())
                {
                    // 开发环境 
                    return BadRequest("用户名不存在");
                }
                else {
                    return BadRequest();
                }
            }
            // 判断锁定
            if (await userManager.IsLockedOutAsync(user))
            {
                return BadRequest($"用户被锁定，锁定结束时间{user.LockoutEnd}");
            }
            // 判断密码是否正确
            if (await userManager.CheckPasswordAsync(user, pwd))
            {
                await userManager.ResetAccessFailedCountAsync(user); //登录成功后充值失败记录次数
                return Ok("登录成功");
            }
            else {
                await userManager.AccessFailedAsync(user); //记录登录失败
                return BadRequest("用户名或者密码错误");
            }
        }

        /// <summary>
        /// 发送修改密码token
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> sendRestPassWordToken(string userName)
        {
            var user=await userManager.FindByNameAsync(userName);
            if (user == null)
            {
                return BadRequest("用户名不存在");
            }
            string token=await userManager.GeneratePasswordResetTokenAsync(user);
            Console.WriteLine($"token={token}");
            return Ok("已发送");
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="token"></param>
        /// <param name="newPassWord"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ActionResult> RestPassWord(string userName, string token, string newPassWord)
        {
            var user = await userManager.FindByNameAsync(userName);
            if (user == null)
            {
                return BadRequest("用户名不存在");
            }
            var result=await userManager.ResetPasswordAsync(user, token, newPassWord);
            if (result.Succeeded)
            { 
                await userManager.ResetAccessFailedCountAsync(user);
                return Ok("重置成功");
            }
            else {
                return BadRequest("重置失败");
            }
        }
        

       
    }

    public record CheckPwdRequest(string UserName, string passWord);


}
